package cn.javav.sso.controller;

import java.util.HashMap;
import java.util.UUID;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import cn.javav.sso.core.utils.TicketUtis;
import cn.javav.sso.entity.Token;
import cn.javav.sso.entity.User;
import cn.javav.sso.services.UserServices;

@Controller
@RequestMapping("/login")
public class LoginController {
	
	@Resource
	private UserServices userServices;
	
	@RequestMapping("/loginPage.do")
	public ModelAndView LoginPage(){
		ModelAndView modelAndView = new ModelAndView();
		modelAndView.setViewName("login");
		return modelAndView;
	}
	
	@RequestMapping("/login.do")
	public ModelAndView doLogin(HttpServletRequest request,String account,String password,String targetUrl){
		System.out.println(account + "  " + password);
		System.out.println(targetUrl);
		ModelAndView modelAndView = new ModelAndView();
		User user = userServices.check(account, password);
		if (user != null) {
			Token token = new Token();
			token.setTokenId(UUID.randomUUID().toString());
			token.setHolder(user);
			token.setDeadline(3600);
			token.setTimestamp(System.currentTimeMillis());
			String ticket = TicketUtis.createTicket();
			token.setTicket(ticket);
			@SuppressWarnings("unchecked")
			HashMap<String, Token> tokens = (HashMap<String, Token>) request.getServletContext().getAttribute("tokens");
			if(tokens == null ){
				tokens = new HashMap<String, Token>();
				tokens.put(ticket, token);
				request.getServletContext().setAttribute("tokens", tokens);
			}
			targetUrl = this.setUrlTicket(targetUrl, ticket);
			modelAndView.addObject("targetUrl", targetUrl);
			modelAndView.setViewName("login_success");
		}else{
			modelAndView.setViewName("login_fail");
		}
		
		return modelAndView;
	}

	private String setUrlTicket(String targetUrl,String ticket){
		String url = null;
		if(targetUrl.contains("?")){
			url=targetUrl+"&ticket="+ticket;
		}else{
			url=targetUrl+"?ticket="+ticket;
		}
		return url;
	}
	
	public UserServices getUserServices() {
		return userServices;
	}

	public void setUserServices(UserServices userServices) {
		this.userServices = userServices;
	}
}
